package com.suyang.syt.listener;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.MySessionContext;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.JsonUtil;

/**
 * 登录验证拦截器
 * 
 * @author Administrator
 * 
 */
public class LogInInterceptor extends HandlerInterceptorAdapter {
	private List<String> excludeUrls;

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = null;
		String sessionID = request.getParameter("sessionID");
		if (EmptyUtil.isNotEmpty(sessionID)) {
			// 通过uploadify上传文件请求
			session = MySessionContext.getSession(sessionID);
		} else {
			session = request.getSession();
		}
		String url = request.getServletPath();
		if (session.getAttribute("loginUser") != null || excludeUrls.contains(url)) {
			return true;
		}
		PrintWriter out = response.getWriter();
		String reequestedWith = request.getHeader("X-Requested-With");
		if (EmptyUtil.isNotEmpty(reequestedWith) && "XMLHttpRequest".equalsIgnoreCase(reequestedWith)) {
			// 处理异步AJAX请求
			out.write(JsonUtil.toJson(new AjaxObj(0, "您还没有登录或登录已超时，请重新登录，然后再刷新本功能！")));
			out.flush();
			out.close();
		} else {
			// 处理其他请求
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			String path = request.getContextPath() + "/login";
			out.write("<script type='text/javascript'>alert('登录超时，请重新登录系统'); window.top.location.href='" + path + "';</script>");
			out.flush();
			out.close();
		}
		return false;
	}
}